import { nextTick } from 'vue';
import { storeToRefs } from 'pinia';
import request from './index';
import router from '@/router';
import crypto from '@/utils/cyptoJs';
import { handleMessage } from '@/utils/globalEvent';
import useUserInfo from '@/stores/userInfo';

// 判断是否本地环境
const { VITE_ENV } = import.meta.env;

const privateRequest = new request({
	baseURL: import.meta.env.VITE_PRIVATE_API,
	timeout: Number(import.meta.env.VITE_TIME_OUT),
	interceptors: {
		requestIntercepor(config) {
			// console.log(config, '单个实例请求成功拦截');
			const { data = undefined } = config;
			// 判断类型是否 formData
			let formData = false;
			if (data) formData = data instanceof FormData;
			// 携带token
			if (VITE_ENV !== 'development' && data && !formData) config.data = crypto.setParams(config.data);
			const stores = useUserInfo();
			const { userInfo } = storeToRefs(stores);
			if (userInfo.value?.token) config.headers['Authorization'] = `Bearer ${userInfo.value.token}`;
			return config;
		},
		requestInterceporCatch(err) {
			console.log('单个实例请求失败拦截');
			return err;
		},
		responseIntercepor(res) {
			// console.log(res, "单个实例响应成功拦截");
			const { code, data } = res.data;
			// 没有权限
			if (code === 401) {
				nextTick(() => {
					router.push('/401');
				});
			}
			if (code !== 200) return handleMessage(data, 'error');
			let value;
			VITE_ENV !== 'development' ? (value = JSON.parse(crypto.getParams(data))) : (value = data);
			return value;
		},
		responseInterceporCatch(err) {
			console.log(err, '单个实例响应失败拦截');
			return new Promise((resolve, reject) => reject(err));
		},
	},
});

export default privateRequest;
